package demo;

import java.util.Collection;
import java.util.HashSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import demo.mybatis.UserDetail;
import demo.mybatis.UserDetailMapper;

@Service
public class DemoUserDetailsService implements UserDetailsService {

	@Autowired
	UserDetailMapper userDetailMapper;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		//get user detail from database
		UserDetail userDetail = userDetailMapper.getUser(username);
		if(userDetail == null){
			throw new UsernameNotFoundException(username + " does not exist");
		}
		
		//create User object for authentication
		Collection<GrantedAuthority> authorities = new HashSet<>();
		authorities.add(new SimpleGrantedAuthority(userDetail.getRole()));
		
		User user = new User(username, userDetail.getPassword(), authorities);
		
		return user;

	}
}
